#!/bin/bash

###########################################
#
#   @file: install_gst_git.sh
#   Author: zbc
#   
###########################################
shellname=$(basename $0)

### configure gst_version
# orc_version="master"
# gst_version="master"
# gst_version="1.16"
# gst_version="1.18"
gst_version="1.19.1"
orc_version="orc-0.4.24"
gst_src="${HOME}/gst"

# Number of threads = cpu core - 1 
core_num=$(grep 'core id' /proc/cpuinfo |wc -l)
thread=$(expr $core_num - 1)
    
mkdir -p ${gst_src}

rm_dir()
{
    for i in "$@"
    do
        if [ "${i}" = "" ];then
            continue
        fi
        if [ -d ${i} ];then
            rm -rf ${i}
        fi
    done
}

check_status()
{
    code=$1

    if [ "X${code}" != "X0" ];then
        echo "Error Code=${code}"
        exit $code
    fi
}

check_version()
{
    v=$1
    if [ "X" = "X${v}" ];then
        return 0
    else
        branch_list=$(git branch)
        check_status $?
        res=$(echo $branch_list |grep -E "^\* ${v}$")
        if [ "$res" = "" ];then
            git checkout $v
            check_status $?
        fi
    fi
}

clone_gst_pkg()
{
    # reference https://gitlab.freedesktop.org/gstreamer
    pkg_name="$1"
    version="$2"
    if [ "" =  "${pkg_name}" ];then
        return 1
    fi
    cd ${gst_src}
    echo -e "\n\n\n------------------------ clone ${pkg_name} ------------------------"
    if [ -d ${gst_src}/${pkg_name} ];then
        cd ${gst_src}/${pkg_name}
        git branch
        if [ $? -ne 0 ];then
            cd ${gst_src}
            rm_dir ${gst_src}/${pkg_name}
            git clone https://gitlab.freedesktop.org/gstreamer/${pkg_name}.git
            check_status $?
        fi
    else
        git clone https://gitlab.freedesktop.org/gstreamer/${pkg_name}.git
        check_status $?
    fi
    
    if [ "${version}" = "" ];then
        return 0
    fi
    
    # Switch branches or restore working tree files
    cd ${gst_src}/${pkg_name}
    git pull
    # git checkout ${version}
    # check_status $?
    check_version ${version}
}

install_meson()
{
    cur_dir=$(pwd)
    meson_version="$1"
    if [ "${meson_version}" = "" ];then
        meson_version="0.57"
    fi
    # skip install if meson version is 0.5x
    install_flag=$(meson --version |grep -E "^0\.5+")
    if [ "${install_flag}" != "" ];then
        return
    fi
    meson_src=~/meson
    cd ~
    echo -e "\n\n\n------------------------ install meson ------------------------"
    # download source code
    if [ -d ${meson_src} ];then
        cd ${meson_src}
        git checkout ${meson_version}
        if [ "X${?}" != "X0" ];then
            cd -
            rm_dir ${meson_src} 
            git clone https://gitee.com/konkajacky/meson.git
            check_status $?
            cd ${meson_src}
            git checkout ${meson_version}
        fi
    else
        git clone https://gitee.com/konkajacky/meson.git
        check_status $?
        cd ${meson_src}
        git checkout ${meson_version}
    fi
    sudo apt install python3-pip -y
    # python3 -m pip install meson
    # python3 setup.py install
    python3 setup.py install --root=dest
    check_status $?
    sudo cp -rv dest/* /
    check_status $?
    echo -e "\n\n\n------------------------ finish meson ------------------------"
    cd ${cur_dir}
}

install_ninja()
{
    cur_dir=$(pwd)
    ninja_version="$1"
    if [ "${ninja_version}" = "" ];then
        ninja_version="release"
    fi
    # ninja --version
    # if [ $? -eq 0 ];then
        # return
    # fi
    
    install_flag=$(ninja --version |grep -E "^${ninja_version}")
    if [ "${install_flag}" != "" ];then
        return
    fi
    
    sudo apt install re2c -y
    
    ninja_src=~/ninja
    cd ~
    rm -rf ~/ninja
    # sudo python3 -m pip install ninja
    echo -e "\n\n\n------------------------ install ninja ------------------------"
    
    if [ -d ${ninja_src} ];then
        cd ${ninja_src}
        git checkout v${ninja_version}
        if [ "X${?}" != "X0" ];then
            cd -
            rm_dir ${ninja_src} 
            git clone https://gitee.com/konkajacky/ninja.git
            check_status $?
            cd ${ninja_src}
            git checkout v${ninja_version}
        fi
    else
        git clone https://gitee.com/konkajacky/ninja.git
        check_status $?
        cd ${ninja_src}
        git checkout v${ninja_version}
    fi
    
    ./configure.py --bootstrap
    check_status $?
    sudo cp ninja /usr/bin/
    
    echo -e "\n\n\n------------------------ finish ninja ------------------------"
    
    cd ${cur_dir}
}

# compile and install current directory source code 
install_obj()
{
    
    if [ -f ./meson.build ];then
        install_meson
        install_ninja "1.8.2"
        # meson build -Dprefix=/usr && ninja -C build && sudo ninja -C build install
        meson build
        check_status $?
        ninja -C build
        check_status $?
        sudo ninja -C build install
        check_status $?
        
    elif [ -f ./autogen.sh ];then
        ./autogen.sh
        if [ $?  -eq 0 ];then
            make -j${thread} && sudo make install
            if [ $?  -eq 0 ];then
                return 0
            else
                ./configure 
                check_status $?
            fi
        else
            ./configure 
            check_status $?
        fi
        make -j${thread} && sudo make install
        check_status $?
    elif [ -f ./configure  ];then
        ./configure 
        check_status $?
        make -j${thread} && sudo make install
        check_status $?
    else
        pwd
        echo "[error] cannot found meson.build or autogen.sh"
        exit 1
    fi
}

build_and_install_pkg()
{
    for i in "$@"
    do
        if [ "${i}" = "" ];then
            continue
        fi
        
        if [ "${i}" = "orc" ];then
            clone_gst_pkg "$i" "${orc_version}"
            install_obj
            continue
        fi
        clone_gst_pkg "$i" "${gst_version}"
        install_obj
    done
}

uninstall_pkg()
{
    # reverse pkg list 
    for i in $(seq $# |tac )
    # for i in "$@"
    do
        pkg_name=$(eval echo '$'"$i")
        if [ "${pkg_name}" = "" ];then
            continue
        fi
        
        pkg_dir="${gst_src}/${pkg_name}"
        if [ ! -d ${pkg_dir} ];then
            continue
        fi
        cd ${pkg_dir}
        echo -e "\n\n\n------------------------ uninstall ${pkg_name} ------------------------"
        
        if [ -f ./meson.build ];then
            sudo ninja -C build uninstall
            sudo ninja -C build  clean
        elif [ -f ./autogen.sh -o -f ./configure ];then
            sudo make uninstall
            make distclean
        else
            pwd
            echo "[error] cannot found meson.build or autogen.sh"
        fi
    done
}

help_msg()
{
msg="
Usage: ./${shellname} [options]

    options:
        install       - download source code and install gstreamer and gst plugins
        uninstall     - uninstall gstreamer and gst plugins

    e.g.
         ./${shellname} install
         ./${shellname} uninstall

"
    echo "${msg}"
}

# main
if [ $# -eq 1 ];then
    exe_type=$(echo "$1" | tr 'A-Z' 'a-z' )
    if [ "${exe_type}" != "install" -a "${exe_type}" != "uninstall" ];then
        echo "[error] unknow option: $1"
        help_msg
        exit 1;
    fi

    echo "${exe_type} gstreamer[y/n]:"
    read choose;
    echo "Your Choice:${choose}"
    choose=$(echo "${choose}" | tr 'A-Z' 'a-z' )
    if [ "X${choose}" != "Xy" ];then
        echo "Cancel ${exe_type}"
        exit 1;
    fi
    
    $(sudo ls)
    
    sudo apt install -y git autoconf autopoint libtool bison flex gtk-doc-tools libglib2.0-dev libssl-dev libva-dev libgtk2.0-dev
    # sudo apt install meson
    
    if [ "Xinstall" = "X${exe_type}" ];then
        echo "install....."
        # install_gst
        build_and_install_pkg "gstreamer" "orc" "gst-plugins-base" "gst-plugins-good" "gst-plugins-ugly" "gst-plugins-bad" "gstreamer-vaapi"
    elif [ "Xuninstall" = "X${exe_type}"  ];then
        echo "uninstall....."
        # uninstall_gst
        uninstall_pkg "gstreamer" "orc" "gst-plugins-base" "gst-plugins-good" "gst-plugins-ugly" "gst-plugins-bad" "gstreamer-vaapi"
    fi
else
    help_msg
fi

